import React from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import { FilterItem } from '../../components'
import { Form, Button, Row, Col, DatePicker, Input, Cascader, Switch,Radio,Icon,Tag,Card,Select,Collapse,Popconfirm,Popover,Checkbox } from 'antd'
import city from '../../utils/city'

const FormItem = Form.Item
const Panel = Collapse.Panel;
const Search = Input.Search
const { RangePicker } = DatePicker
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const ButtonGroup = Button.Group;
const Option = Select.Option;
const CheckboxGroup = Checkbox.Group;
const formItemLayout = {
  labelCol: {
    span: 5,
  },
  wrapperCol: {
    span: 19,
  },
}

const formItemNoLabelLayout = {
  labelCol: {
    span: 5,
  },
  wrapperCol: {
    span: 19,
  },
}

const ColProps = {
  xs: 24,
  sm: 12,
  style: {
    marginBottom: 16,
  },
}

const customPanelStyle = {
  background: '#f7f7f7',
  borderRadius: 4,
  marginBottom: 24,
  border: 0,
};

const TwoColProps = {
  ...ColProps,
  xl: 96,
}

const Filter = ({
  onAdd,
  isMotion,
  switchIsMotion,
  onFilterChange,
  filter,
  // 组管理
  onAddGroup,
  onShowGroup,
  onCancelGroup,
  groupVisible,
  selectGroupVisible,
  groupList,
  checkedGroupList,
  onShowSelectGroups,
  onCancelSelectGroup,
  onConfirmSelectGroup,

  // 标签管理
  onAddTag,
  onShowTag,
  onCancelTag,
  tagVisible,
  selectTagVisible,
  tagList,
  checkedTagList,
  onShowSelectTags,
  onCancelSelectTag,
  onConfirmSelectTag,
  form: {
    getFieldDecorator,
    getFieldsValue,
    setFieldsValue,
    validateFields
  },
}) => {
  const handleFields = (fields) => {
    const { timeValue } = fields
    if (timeValue.length) {
      fields.between_timeValue = new Date(timeValue[0].format('YYYY-MM-DD')).getTime()
      fields.between_timeValueEnd = new Date(timeValue[1].format('YYYY-MM-DD')).getTime()
    }
    return fields
  }

  const handleSubmit = () => {
    debugger
    let fields = getFieldsValue()
    fields = handleFields(fields)
    onFilterChange(fields)
  }

  const handleReset = () => {
    const fields = getFieldsValue()
    for (let item in fields) {
      if ({}.hasOwnProperty.call(fields, item)) {
        if (fields[item] instanceof Array) {
          fields[item] = []
        } else {
          fields[item] = undefined
        }
      }
    }
    setFieldsValue(fields)
    handleSubmit()
  }

  const handleChange = (key, values) => {
    // let fields = getFieldsValue()
    // fields[key] = values
    // fields = handleFields(fields)
    // onFilterChange(fields)
  }

  const onChange = (e) => {
    console.log(`radio checked:${e.target.value}`);
  }

  const { name, address } = filter

  let initialCreateTime = []
  if (filter.createTime && filter.createTime[0]) {
    initialCreateTime[0] = moment(filter.createTime[0])
  }
  if (filter.createTime && filter.createTime[1]) {
    initialCreateTime[1] = moment(filter.createTime[1])
  }

  const remarkDataArr = [{key:"all",value:"选择备注项"},{key:"address",value:"地址"},{key:"age",value:"年龄"}
    ,{key:"bloodType",value:"血型"},{key:"company",value:"公司"},{key:"constellation",value:"星座"},{key:"email",value:"邮箱"}
    ,{key:"hobby",value:"爱好"},{key:"idCard",value:"身份证号"},{key:"introduction",value:"简介"},{key:"phone",value:"手机"}
    ,{key:"name",value:"姓名"},{key:"occupation",value:"职业"},{key:"position",value:"职位"},{key:"qq",value:"qq"}
    ,{key:"graduated",value:"毕业院校"},{key:"wechat",value:"微信"}];
  const remarkDatas = [];
  for (var value of remarkDataArr) {
    remarkDatas.push(<Option key={value.key}>{value.value}</Option>);
  }

  let followType = '全部'
  let timeType = '不限'
  let timeValue = []
  let interactionTimes =  0
  let interactionTimesEnd = 0
  let interactionTimesEnable = false

  // 交互次数
  const interactionTimesChange = (e) => {
    if(e.target.value != "all") {
      interactionTimesEnable = true;
    } else {
      interactionTimesEnable = false;
    }
  }

  // 添加分组
  const  addGroup = () => {
    validateFields((errors) => {
      debugger
      if (errors) {
        return
      }
      debugger;
      let fields = getFieldsValue()
      let data = {name:fields.groupName}
      onAddGroup(data)
      console.log("创建新分组:"+fields.groupName)
    })
  }

  // 打开组
  const  showGroup = () => {
    setFieldsValue({groupName:''})
    onShowGroup()
    console.log("打开组")
  }

  // 关闭分组
  const  cancelGroup = () => {
    setFieldsValue({groupName:''})
    onCancelGroup()
    console.log("取消新分组")
  }

  // 打开选择组
  const showSelectGroups = () => {
    onShowSelectGroups();
  }

  // 关闭选择组
  const  cancelShowGroup = () => {
    onCancelSelectGroup()
    console.log("取消选择分组")
  }

  // 确认选择分组
  const confirmSelectGroup = () => {
    debugger
    let fields = getFieldsValue()
    checkedGroupList = fields.groupList
    let data = []
    checkedGroupList.map(function (value) {
      data.push({label:value,value:value})
    })

    onConfirmSelectGroup(data);
  }

  // 添加标签
  const  addTag = () => {
    validateFields((errors) => {
      debugger
      if (errors) {
        return
      }
      debugger;
      let fields = getFieldsValue()
      let data = {name:fields.tagName}
      onAddTag(data)
      console.log("创建新标签:"+fields.tagName)
    })
  }

  // 打开标签
  const  showTag = () => {
    setFieldsValue({tagName:''})
    onShowTag()
    console.log("打开标签")
  }

  // 关闭分组
  const  cancelTag = () => {
    setFieldsValue({tagName:''})
    onCancelTag()
    console.log("取消新标签")
  }

  // 打开选择组
  const showSelectTags = () => {
    onShowSelectTags();
  }

  // 关闭选择组
  const  cancelShowTag = () => {
    onCancelSelectTag()
    console.log("取消选择标签")
  }

  // 确认选择分组
  const confirmSelectTag = () => {

    let fields = getFieldsValue()
    checkedTagList = fields.tagList
    let data = []
    checkedTagList.map(function (value) {
      data.push({label:value,value:value})
    })

    onConfirmSelectTag(data);
  }

  const content = (
    <div>
      <Form layout="horizontal">
        <FormItem>
          {getFieldDecorator('groupName', {
            rules: [
              {
                required: true,
                message: '必须填入组名称!',
              },
            ],
          })(
            <Input
              style={{ width: 200 }}
            />
          )}
        </FormItem>
        </Form>
      <div style={{marginTop:10}}>
        <Button onClick={cancelGroup} size="small" type="primary">取消</Button><Button style={{marginLeft:10}} size="small" type="primary" onClick={addGroup}>确定</Button>
      </div>
    </div>
  );

  // 组列表
  const groupListContent = (
    <div>
      <Form layout="horizontal">
            <FormItem>
              {getFieldDecorator('groupList')(
                <CheckboxGroup options={groupList}  />
              )}
            </FormItem>
      </Form>
      <div style={{marginTop:10}}>
        <Button onClick={onCancelSelectGroup} size="small" type="primary">取消</Button><Button style={{marginLeft:10}} size="small" type="primary" onClick={confirmSelectGroup}>确定</Button>
      </div>
    </div>
  );

  // 标签
  const tagContent = (
    <div>
      <Form layout="horizontal">
        <FormItem>
          {getFieldDecorator('tagName', {
            rules: [
              {
                required: true,
                message: '必须填入标签名称!',
              },
            ],
          })(
            <Input
              style={{ width: 200 }}
            />
          )}
        </FormItem>
      </Form>
      <div style={{marginTop:10}}>
        <Button onClick={cancelTag} size="small" type="primary">取消</Button><Button style={{marginLeft:10}} size="small" type="primary" onClick={addTag}>确定</Button>
      </div>
    </div>
  );

  // 标签列表
  const tagListContent = (
    <div>
      <Form layout="horizontal">
        <FormItem>
          {getFieldDecorator('tagList')(
            <CheckboxGroup options={tagList}  />
          )}
        </FormItem>
      </Form>
      <div style={{marginTop:10}}>
        <Button onClick={onCancelSelectTag} size="small" type="primary">取消</Button><Button style={{marginLeft:10}} size="small" type="primary" onClick={confirmSelectTag}>确定</Button>
      </div>
    </div>
  );
  return (
    <Row gutter={24} style={{padding:"10px"}}>
      <Collapse bordered={true} defaultActiveKey={['1']} >
        <Panel header="折叠查询条件" key="1" style={customPanelStyle}>
      <Col span={12}>
        <Card title="查询条件" noHovering bordered={true} bodyStyle={{
          padding: '24px 36px 24px 24px',marginButtom:'20px'
        }}>
          <Form layout="horizontal">
            <FormItem label="关注状态" hasFeedback {...formItemLayout}>
              {
                <div>
                  {getFieldDecorator('equal_followType', { initialValue: followType })(
                    <Select
                      showSearch
                      defaultValue="-1"
                      style={{ width: 100 }}
                      placeholder="全部"
                    >
                      <Option value="-1">全部</Option>
                      <Option value="0">已关注</Option>
                      <Option value="1">取消关注</Option>
                    </Select>
                  )}
                </div>
              }
            </FormItem>
            <FormItem label="筛选时间" hasFeedback {...formItemLayout}>
              {
                <div>
                  {getFieldDecorator('equal_timeType', { initialValue: timeType })(
                    <Select
                      showSearch
                      style={{ width: 100 }}
                      defaultValue="all"
                      placeholder="选择时间"
                    >
                      <Option value="all">不限</Option>
                      <Option value="attentionTime">关注时间</Option>
                      <Option value="cancelAttentionTime">取关时间</Option>
                      <Option value="leastActionTime">最近互动时间</Option>
                    </Select>
                  )}
                  {getFieldDecorator('timeValue', { initialValue: timeValue })(
                    <RangePicker
                      ranges={{ 今天: [moment(), moment()],
                  '一周内': [moment().add(-7,'days'),moment()],
                  '两周内': [moment().add(-14,'days'),moment()],
                  '一月内': [moment().add(-1,'month'),moment()],
                  '当月': [moment().startOf('month'),moment()] }}
                      style={{ width: '75%' }} size="large" onChange={handleChange.bind('null', 'timeValue')}/>
                  )}
                </div>
              }
            </FormItem>
            <FormItem label="互动次数" hasFeedback {...formItemLayout}>
              {
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  {getFieldDecorator('equal_interactionTimes',)(
                    <Select
                      showSearch
                      defaultValue="all"
                      style={{ width: 100 }}
                      placeholder="不限"
                      onChange={interactionTimesChange}
                    >
                      <Option value="all">不限</Option>
                      <Option value="in">等于</Option>
                      <Option value="not_in">大于</Option>
                      <Option value="not_in">小于</Option>
                      <Option value="not_in">范围</Option>
                    </Select>
                  )}

                  {getFieldDecorator('interactionTimes', { initialValue: interactionTimes,rules: [
                  {
                    type: 'number',
                  },
                    ], })(
                    <Input
                      style={{ width: 100 }}
                      disabled={interactionTimesEnable}
                    />
                  )}

                  {getFieldDecorator('interactionTimesEnd', { initialValue: interactionTimes,rules: [
                    {
                      type: 'number',
                    },
                  ], })(
                    <Input
                      style={{ width: 100 }}
                      disabled={interactionTimesEnable}
                    />
                  )}
                </div>
              }
            </FormItem>
            <FormItem label="标签数" hasFeedback {...formItemLayout}>
              {
                <div>
                  <Select
                    showSearch
                    defaultValue="all"
                    style={{ width: 100 }}
                    placeholder="不限"
                  >
                    <Option value="all">不限</Option>
                    <Option value="in">等于</Option>
                    <Option value="not_in">大于</Option>
                    <Option value="not_in">小于</Option>
                    <Option value="not_in">范围</Option>
                  </Select>
                </div>
              }
            </FormItem>
            <FormItem label="地域" hasFeedback {...formItemLayout}>
              {
                <div>
                  <Select
                    showSearch
                    style={{ width: 200 }}
                    placeholder="选择地区"
                    optionFilterProp="children"
                  >
                    <Option value="jack">Jack</Option>
                    <Option value="lucy">Lucy</Option>
                    <Option value="tom">Tom</Option>
                  </Select>
                </div>
              }
            </FormItem>
            <FormItem label="性別" hasFeedback {...formItemLayout}>
              { <div>
                <RadioGroup onChange={onChange} defaultValue="all">
                  <RadioButton  value="all">全部</RadioButton>
                  <RadioButton value="male">男</RadioButton>
                  <RadioButton value="female">女</RadioButton>
                  <RadioButton value="unknown">未知</RadioButton>
                </RadioGroup>
              </div>
              }
            </FormItem>
            <FormItem label="查询昵称/openid" hasFeedback {...formItemLayout}>
              { <div>
               <Input placeholder="昵称/openid" />
              </div>
              }
            </FormItem>
            <FormItem label="搜索备注" hasFeedback {...formItemLayout}>
              {
                <div>
                  <Select
                    showSearch
                    defaultValue="all"
                    style={{ width: 100 }}
                    placeholder="选择备注项"
                    optionFilterProp="children"
                    onChange={handleChange}
                  >
                    {remarkDatas}
                  </Select>
                </div>
              }
            </FormItem>
            <FormItem label="" hasFeedback {...formItemLayout}>
              {
                <div>
                  <Button type="primary" size="large" style={{marginRight:'40px'}} className="margin-right" onClick={handleSubmit}>查询</Button>
                </div>
              }
            </FormItem>
          </Form>
        </Card>
        </Col>
      <Col span={12}>
      <Card title="组合标签" noHovering bordered={true} bodyStyle={{
          padding: '24px 36px 24px 24px',marginButtom:'20px'
        }}>
        <Form layout="horizontal">
          <FormItem label="分组" hasFeedback {...formItemLayout}>
            {
              <div  style={{ display: 'flex', justifyContent: 'space-between' }}>
                <Popover
                  visible = {selectGroupVisible}
                  placement="topLeft" title="选择分组" content={groupListContent} arrowPointAtCenter trigger="click">
                  <Button onClick={showSelectGroups} type="primary">选择分组</Button>
                </Popover>
                  <Popover
                    visible = {groupVisible}
                    placement="topLeft" title="创建新分组" content={content} arrowPointAtCenter trigger="click">
                    <Button onClick={showGroup} type="primary">创建分组</Button>
                  </Popover>
              </div>
            }
          </FormItem>
          <FormItem label={checkedGroupList.length > 0 ? '选中的组':''} hasFeedback {...formItemNoLabelLayout}>
            {
              <div style={{marginLeft:'60px'}}>
                {
                  checkedGroupList.map(function (value) {
                    return <Tag color="green">{value.value}</Tag>
                  })
                }
              </div>
            }
          </FormItem>
          <FormItem label="标签" hasFeedback {...formItemLayout}>
            {
              <div  style={{ display: 'flex', justifyContent: 'space-between' }}>
                <Popover
                  visible = {selectTagVisible}
                  placement="topLeft" title="选择标签" content={tagListContent} arrowPointAtCenter trigger="click">
                  <Button onClick={showSelectTags} type="primary">选择标签</Button>
                </Popover>
                <Popover
                  visible = {tagVisible}
                  placement="topLeft" title="创建新标签" content={tagContent} arrowPointAtCenter trigger="click">
                  <Button onClick={showTag} type="primary">创建标签</Button>
                </Popover>
              </div>
            }
          </FormItem>
          <FormItem label={checkedTagList.length > 0 ? '选中的标签':''} hasFeedback {...formItemNoLabelLayout}>
            {
              <div style={{marginLeft:'60px'}}>
                {
                  checkedTagList.map(function (value) {
                    return <Tag color="green">{value.value}</Tag>
                  })
                }
              </div>
            }
          </FormItem>
        </Form>
      </Card>
    </Col>
        </Panel>
      </Collapse>
    </Row>
  )
}

Filter.propTypes = {
  onAdd: PropTypes.func,
  isMotion: PropTypes.bool,
  switchIsMotion: PropTypes.func,
  form: PropTypes.object,
  filter: PropTypes.object,
  onFilterChange: PropTypes.func,
}

export default Form.create()(Filter)
